//
//  ChartView.m
//  UHealth
//
//  Created by liliang on 15/2/9.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "ChartView.h"
#import "CorePlot-CocoaTouch.h"
#import "BodyTemperatureObj.h"
#import "NSString+BloodSugar.h"

@interface ChartView ()<CPTScatterPlotDataSource,CPTAxisDelegate>

@property (nonatomic, strong)NSArray        *dataArray;
@property (nonatomic, strong)CPTXYGraph     *graph;
@property (nonatomic, strong)CPTScatterPlot *scatterPlot;

@end

@implementation ChartView

- (instancetype)initWithFrame:(CGRect)frame dataArray:(NSArray *)dataArray
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.dataArray = dataArray;
        [self createPlotViewWithFrame:frame];
    }
    return self;
}

- (void)createPlotViewWithFrame:(CGRect)frame
{
    _graph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
    
    CPTTheme *theme = [CPTTheme themeNamed:kCPTPlainWhiteTheme];
    [_graph applyTheme:theme];
    
    UIView *drawView = [[CPTGraphHostingView alloc] initWithFrame:frame];
    [self addSubview:drawView];
    CPTGraphHostingView *hostingView = (CPTGraphHostingView *)drawView;
    hostingView.allowPinchScaling = NO;
    [hostingView setHostedGraph:_graph];
    
    //线条的样式
    CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
    lineStyle.lineColor = [CPTColor colorWithComponentRed:191/255.0f green:191/255.0f blue:191/255.0f alpha:1.0];
    lineStyle.lineWidth = 1.0;
    self.graph.plotAreaFrame.plotArea.borderLineStyle = lineStyle;
    
    self.graph.plotAreaFrame.masksToBorder = NO;
    self.graph.paddingBottom = 0.0;
    self.graph.paddingLeft   = 50.0;
    self.graph.paddingRight  = 15.0;
    self.graph.paddingTop    = 0.0;
    self.graph.plotAreaFrame.borderLineStyle = nil;
    self.graph.plotAreaFrame.cornerRadius    = 0;
    
    self.graph.plotAreaFrame.paddingTop    = 10.0;
    self.graph.plotAreaFrame.paddingRight  = 0.0;
    self.graph.plotAreaFrame.paddingLeft   = 0.0;
    self.graph.plotAreaFrame.paddingBottom = 40.0;
    
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
    plotSpace.allowsUserInteraction = YES;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(15)];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(12)];
    plotSpace.globalYRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(30) length:CPTDecimalFromInt(12)];
    
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet ;
    CPTXYAxis *xAxis = axisSet.xAxis;
    CPTMutableLineStyle *xLineStyle   = [[CPTMutableLineStyle alloc] init];
    xLineStyle.lineColor              = [CPTColor colorWithComponentRed:191/255.0f green:191/255.0f blue:191/255.0f alpha:1.0];
    xLineStyle.lineWidth              = 1.0;
    xAxis.axisLineStyle               = xLineStyle;
    xAxis.labelingPolicy              = CPTAxisLabelingPolicyNone;
    xAxis.axisConstraints             = [CPTConstraints constraintWithLowerOffset:0.0];
    xAxis.majorTickLineStyle          = xLineStyle;
    xAxis.majorTickLength             = 5;
    xAxis.minorTickLineStyle          = nil;
    xAxis.orthogonalCoordinateDecimal = CPTDecimalFromInt(30);
    
    CPTXYAxis *yAxis                  = axisSet.yAxis;
    yAxis.axisConstraints             = [CPTConstraints constraintWithLowerOffset:0.0];
    yAxis.axisLineStyle               = xLineStyle;
    yAxis.majorTickLineStyle          = nil;
    yAxis.majorTickLength             = 1.0;
    yAxis.minorTickLineStyle          = nil;//  不显示小刻度线
    yAxis.majorIntervalLength         = CPTDecimalFromString(@"2.0");
    yAxis.minorTicksPerInterval       = 1;
    yAxis.delegate                    = self;
    yAxis.orthogonalCoordinateDecimal = CPTDecimalFromInt(0);
//    yAxis.title                       = @"单位:℃";
    
//    lineStyle.lineWidth      = 1.0;
//    xAxis.axisLineStyle      = lineStyle;
//    yAxis.axisLineStyle      = lineStyle;
    
    NSMutableArray *labelArray = [NSMutableArray array];
    NSMutableArray *dateArray  = [NSMutableArray array];
    for (NSInteger i = 0; i < self.dataArray.count; i++) {
        BodyTemperatureObj *obj = self.dataArray[i];
        NSString *dateStr = [[NSString stringFromDate:obj.measureDate] substringWithRange:NSMakeRange(11, 8)];
        [dateArray addObject:dateStr];
    }
    float labelLocation = 1;
    CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
    textStyle.fontSize = 12;
    textStyle.color = [CPTColor colorWithComponentRed:129/255.0f green:129/255.0f blue:129/255.0f alpha:1.0];
    yAxis.titleTextStyle  = textStyle;
    for (NSString *dateStr in dateArray) {
        CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:dateStr textStyle:textStyle];
        label.tickLocation = [[NSNumber numberWithFloat:labelLocation] decimalValue];
        label.offset = xAxis.labelOffset + xAxis.majorTickLength;
        label.rotation = M_PI/4.0;
        [labelArray addObject:label];
        labelLocation += 1.5;
    }
    xAxis.axisLabels = [NSSet setWithArray:labelArray];
    if (labelLocation < 15) {
        plotSpace.globalXRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(15)];
    }
    else {
        plotSpace.globalXRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(0) length:CPTDecimalFromInt(labelLocation)];
    }
    
    self.scatterPlot = [[CPTScatterPlot alloc] init];
    self.scatterPlot.identifier = @"Blue Plot";
    
    CPTMutableLineStyle *dataLineStyle = [CPTMutableLineStyle lineStyle];
    dataLineStyle.lineColor = [CPTColor colorWithComponentRed:36/255.0f green:174/255.0f blue:238/255.0f alpha:1];
    dataLineStyle.lineWidth = 1;
    self.scatterPlot.dataLineStyle = dataLineStyle;
    self.scatterPlot.dataSource = self;
    [self.graph addPlot:self.scatterPlot];
    
    //点上画圈
    CPTMutableLineStyle  *symbolLineStyle = [CPTMutableLineStyle lineStyle];
    symbolLineStyle.lineColor = [CPTColor colorWithComponentRed:233/255.0 green:98/255.0 blue:104/255.0 alpha:1];
    symbolLineStyle.lineWidth = 0.5f;
    CPTPlotSymbol *plotSymbol = [CPTPlotSymbol ellipsePlotSymbol];
    plotSymbol.fill = [CPTFill fillWithColor:[CPTColor colorWithComponentRed:233/255.0 green:98/255.0 blue:104/255.0 alpha:1]];
    plotSymbol.lineStyle = symbolLineStyle;
    plotSymbol.size = CGSizeMake(3.0, 3.0);
    self.scatterPlot.plotSymbol = plotSymbol;
    
    //网格线
    CPTMutableLineStyle *gridLineStyle = [CPTMutableLineStyle lineStyle];
    gridLineStyle.lineColor = [CPTColor colorWithComponentRed:191/255.0 green:191/255.0 blue:191/255.0 alpha:1];
    gridLineStyle.lineWidth = 0.5f;
    yAxis.majorGridLineStyle = gridLineStyle;
    xAxis.majorGridLineStyle = gridLineStyle;
}

- (void)refreshViewWithDataArray:(NSArray *)dataArray
{
    self.dataArray = dataArray;
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet ;
    CPTXYAxis *xAxis = axisSet.xAxis;
    NSMutableArray *labelArray = [NSMutableArray array];
    NSMutableArray *dateArray  = [NSMutableArray array];
    for (NSInteger i = 0; i < self.dataArray.count; i++) {
        BodyTemperatureObj *obj = self.dataArray[i];
        NSString *dateStr = [[NSString stringFromDate:obj.measureDate] substringWithRange:NSMakeRange(11, 8)];
        [dateArray addObject:dateStr];
    }
    float labelLocation = 1;
    CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
    textStyle.fontSize = 10;
    textStyle.color = [CPTColor colorWithComponentRed:200/255.0f green:200/255.0f blue:200/255.0f alpha:1.0];
    for (NSString *dateStr in dateArray) {
        CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:dateStr textStyle:textStyle];
        label.tickLocation = [[NSNumber numberWithFloat:labelLocation] decimalValue];
        label.offset = xAxis.labelOffset + xAxis.majorTickLength;
        label.rotation = M_PI/4.0;
        [labelArray addObject:label];
        labelLocation += 1.5;
    }
    xAxis.axisLabels = [NSSet setWithArray:labelArray];
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(labelLocation - 15.0)
                                                    length:CPTDecimalFromDouble(15.0)];
    //    int xmax = self.dataArray.count;
    plotSpace.globalXRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat (0.0f) length:CPTDecimalFromFloat(labelLocation+3)];
    
    [_graph reloadData];
}

- (void)setGraphTitle:(NSString *)title
{
//    _graph.title = title;
//    CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
//    textStyle.fontSize = 15;
//    textStyle.color = [CPTColor colorWithComponentRed:200/255.0f green:200/255.0f blue:200/255.0f alpha:1.0];
//    _graph.titleTextStyle = textStyle;
}

- (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
    return self.dataArray.count;
}

- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx
{
    NSDecimalNumber *number = nil;
    if ([plot isKindOfClass:[CPTScatterPlot class]]) {
        switch (fieldEnum) {
            case CPTScatterPlotFieldX:
                number=(NSDecimalNumber *)[NSDecimalNumber numberWithFloat:1.5*idx + 1];    // X轴上的数值表示
                break;
            case CPTScatterPlotFieldY:
                if ([plot.identifier isEqual:@"Blue Plot"]) {
                    //                    BloodSugarDataObj *obj = self.dataArray[idx];
                    BodyTemperatureObj *obj = self.dataArray[idx];
                    float bloodSugarValue = obj.bodyTemperatureValue;
                    number = (NSDecimalNumber *)[NSDecimalNumber numberWithFloat:bloodSugarValue];
                }
                break;
            default:
                break;
        }
    }
    return number;
}

- (CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)idx
{
    static CPTTextStyle *whiteText = nil;
    if (!whiteText) {
        whiteText = [[CPTTextStyle alloc] init];
    }
    CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
    textStyle.color = [CPTColor colorWithComponentRed:143/255.0 green:143/255.0 blue:143/255.0 alpha:1];
    textStyle.fontSize = 10.0f;
    CPTTextLayer *newLayer = nil;
    NSString *identifier = (NSString *)[plot identifier];
    if ([identifier isEqualToString:@"Blue Plot"]) {
        BodyTemperatureObj *obj = self.dataArray[idx];
        newLayer = [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:@"%.1f",obj.bodyTemperatureValue] style:whiteText];
        newLayer.textStyle = textStyle;
    }
    return newLayer;
}

#pragma mark -- CPTAxisDelegate
- (BOOL)axis:(CPTAxis *)axis shouldUpdateAxisLabelsAtLocations:(NSSet *)locations
{
    static CPTTextStyle * positiveStyle = nil;
    NSNumberFormatter * formatter   = axis.labelFormatter;
    CGFloat labelOffset             = axis.labelOffset;
    NSMutableSet * newLabels        = [NSMutableSet set];
    for (NSDecimalNumber * tickLocation in locations) {
        CPTTextStyle *theLabelTextStyle;
        if (!positiveStyle) {
            CPTMutableTextStyle * newStyle = [axis.labelTextStyle mutableCopy];
            newStyle.color = [CPTColor colorWithComponentRed:200/255.0f green:200/255.0f blue:200/255.0f alpha:1.0];
            positiveStyle  = newStyle;
        }
        theLabelTextStyle = positiveStyle;
        NSString * labelString      = [formatter stringForObjectValue:tickLocation];
        CPTTextLayer * newLabelLayer= [[CPTTextLayer alloc] initWithText:labelString style:theLabelTextStyle];
        
        CPTAxisLabel * newLabel     = [[CPTAxisLabel alloc] initWithContentLayer:newLabelLayer];
        newLabel.tickLocation       = tickLocation.decimalValue;
        newLabel.offset             = labelOffset;
        
        [newLabels addObject:newLabel];
    }
    axis.axisLabels = newLabels;
    
    return NO;
    
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
